/**
* AutoSWF - Cody Cushing. March 26, 2009
* Copyright (c) 2009 Cody Cushing
* No use restrictions. Maintain this notice in all versions. 
**/

package com.autoswf.taskrunner.loadtasks
{
	import com.autoswf.taskrunner.ITask;
	import com.autoswf.taskrunner.TaskEvent;
	
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;

	/**
	 * Generic utf data loader task.
	 */
	public class URLLoaderTask extends EventDispatcher implements ITask
	{
		protected var _urlLoader:URLLoader;
		protected var _loadRequest:LoadRequest;
		
		
		/**
		 * Constructor.
		 */		
		public function URLLoaderTask(loadRequest:LoadRequest)
		{
			_loadRequest = loadRequest;
			
			_urlLoader = new URLLoader();
			_urlLoader.addEventListener(Event.COMPLETE, urlLoader_completeHandler);
			_urlLoader.addEventListener(IOErrorEvent.IO_ERROR, urlLoader_errorHandler);
			_urlLoader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, urlLoader_errorHandler);
		}
		
		
		public function run():void
		{
			_urlLoader.load(new URLRequest(_loadRequest.uri));
		}
		
		
		public function get result():*
		{
			return _urlLoader.data;
		}
		
		
		public function get id():String
		{
			return _loadRequest.id;
		}
		
		
		protected function urlLoader_completeHandler(event:Event):void
		{
			dispatchEvent(new TaskEvent(TaskEvent.TASK_COMPLETE, _loadRequest.id));
		}

		protected function urlLoader_errorHandler(event:Event):void
		{
			dispatchEvent(new TaskEvent(TaskEvent.TASK_FAILURE, _loadRequest.id));
		}
	}
}


